import * as React from 'react'
import { message, Icon, Upload, Modal } from 'antd'
import { serverIP, Cache } from '..'
export class SignleUpload extends React.Component<any, any> {
  state={
    loading: false,
    files:[],
    imageUrl:"",
    previewVisible:false,
  }
  getBase64 = (img: Blob, callback: Function)=> {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }
  beforeUpload=(file: Blob)=>{
    const isJPG = (file.type === 'image/jpeg' || file.type ==='image/png' || file.type ==='image/gif' || file.type ==='image/bmp' || file.type ==='image/jpeg')
    if (!isJPG) {
      message.error("请上传图片类型文件")
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error("文件大小不允许超过2M")
    }
    return isJPG && isLt2M
  }
  handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true })
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, (imageUrl: string) => this.setState({
        imageUrl,
        loading: false,
      }))
      this.setState({files:info.file.response.files})
    }
  }
  setFiles = (file_obj: any)=>{
    if(file_obj.guid==null || file_obj.guid=="") return
    let files: any=this.state.files
    files.push({ guid: file_obj.guid })
    this.setState({ files,imageUrl: file_obj.imageUrl })
  }
  getFiles=()=>{
    return this.state.files
  }
  clearFiles=()=>{
    this.setState({files:[],imageUrl:''})
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">{this.props.name}</div>
      </div>
    )
    const imageUrl = this.state.imageUrl
    return (
      <div style={{float:"left"}}>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={`${serverIP}/VScm/YYSQ/Upload`}
        headers={{'token':Cache.sessionGet('LOGIN_USER').token}}
        beforeUpload={this.beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? <div>
          <img src={imageUrl} alt="" style={{maxWidth:"128px",maxHeight:"128px"}} />
          <div style={{width:"100%",fontWeight:"bolder"}}><a onClick={(e)=>{
            e.stopPropagation()
            this.setState({ previewVisible: true })
          }}>{this.props.name}</a></div>
        </div> : uploadButton}
      </Upload>
      <Modal visible={this.state.previewVisible} footer={null} onCancel={()=>{
        this.setState({ previewVisible: false })
      }}>
        <img alt={this.props.name} style={{ width: '100%' }} src={imageUrl} />
      </Modal>
    </div>
    )
  }
}